package DataType;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class MessageFormat {

	// static ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
	public static ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN;
	public static int packetHeaderLen = 16;

	public static String encoding = "UTF-8";

	public static boolean isHeartBeatMessage(byte[] data) {
		ByteBuffer bb = ByteBuffer.wrap(data);
		bb.order(byteOrder);
		byte[] tmp = new byte[6];
		bb.get(tmp, 0, 6);
		if ((tmp[0] != Byte.valueOf("00", 16))
				|| (tmp[1] != Byte.valueOf("43", 16))
				|| (tmp[2] != Byte.valueOf("45", 16))
				|| (tmp[3] != Byte.valueOf("54", 16))
				|| (tmp[4] != Byte.valueOf("43", 16))
				|| (tmp[5] != Byte.valueOf("00", 16))) {
			return false;
		}
		bb.get(tmp, 0, 4);
		if ((tmp[0] != Byte.valueOf("00", 16))
				|| (tmp[1] != Byte.valueOf("01", 16))
				|| (tmp[2] != Byte.valueOf("00", 16))
				|| (tmp[3] != Byte.valueOf("01", 16))) {
			return false;
		}
		bb.getInt(); // no sense
		short len = bb.getShort();
		if (len != 2)
			return false;
		else
			return true;
	}

	public static int byteArrayToPacketLen(byte[] data) {
		ByteBuffer bb = ByteBuffer.wrap(data);
		bb.order(byteOrder);
		byte[] tmp = new byte[6];
		bb.get(tmp, 0, 6);
		if ((tmp[0] != Byte.valueOf("00", 16))
				|| (tmp[1] != Byte.valueOf("43", 16))
				|| (tmp[2] != Byte.valueOf("45", 16))
				|| (tmp[3] != Byte.valueOf("54", 16))
				|| (tmp[4] != Byte.valueOf("43", 16))
				|| (tmp[5] != Byte.valueOf("00", 16))) {
			System.out.println(tmp[0] + "," + tmp[1] + "," + tmp[2] + ","
					+ tmp[3] + "," + tmp[4] + "," + tmp[5]);
			System.exit(0);
			return -1;
		}
		bb.getInt();
		bb.getInt();
		short len = bb.getShort();
		return len;
	}

	private static int byteArrayToInt(byte[] b) { // message header should be 4
													// bytes
		final ByteBuffer bb = ByteBuffer.wrap(b);
		bb.order(byteOrder);
		return bb.getInt();
	}

	public static byte[] hexStringToByteArray(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.substring(2).toUpperCase();
		char[] hexChars = hexString.toCharArray();
		byte[] array = new byte[hexChars.length / 2];
		for (int i = 0; i < hexChars.length / 2; i++) {
			array[i] = (byte) (charToByte(hexChars[2 * i]) << 4 | charToByte(hexChars[2 * i + 1]));
		}
		return array;
	}

	public static byte hexStringToByte(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return 0;
		}
		hexString = hexString.substring(2).toUpperCase();
		char[] hexChars = hexString.toCharArray();
		byte d = (byte) (charToByte(hexChars[0]) << 4 | charToByte(hexChars[1]));
		return d;
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

}
